package com.taorenqi.business.fragment.mine.more;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.taorenqi.business.R;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.event.StartFragmentEvent;
import com.taorenqi.business.fragment.base.BaseBackFragment;
import com.taorenqi.business.fragment.login.ModifySuccessfullyFragment;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.utils.ValidatorUtils;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.business.widget.verifycode.Rotate;
import com.taorenqi.data.cache.ACache;
import com.taorenqi.data.cache.EnumKey;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.login.CodeDataEntity;
import com.taorenqi.data.requestmsgtoken.RegisterDataHttpRequest;
import com.taorenqi.data.service.LoginDataHttpRequest;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class ChangePhoneFragment extends BaseBackFragment {


    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.change_phone_mobile)
    EditText changePhoneMobile;
    @Bind(R.id.change_phone_tuxing)
    EditText changePhoneTuxing;
    @Bind(R.id.change_phone_yzm)
    ImageView changePhoneYzm;
    @Bind(R.id.change_phone_et_msg)
    EditText changePhoneEtMsg;
    @Bind(R.id.change_phone_msg)
    TextView changePhoneMsg;
    @Bind(R.id.change_phone_sumit)
    TextView changePhoneSumit;
    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriberReg;
    private BasePageableResponse<CodeDataEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriberCode;
    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriber;

    private String token;
    private int time = 60;
    private int flag;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    if (time == 0) {
                        time = 60;
                        if (changePhoneMsg != null) {
                            changePhoneMsg.setClickable(true);
                            changePhoneMsg.setText("获取验证码");
                        }
                    } else {
                        if (changePhoneMsg != null) {
                            changePhoneMsg.setText("重新获取(" + (--time) + ")");
                            handler.sendEmptyMessageDelayed(100, 1000);
                        }
                    }
                    break;
            }
        }
    };
    public static ChangePhoneFragment newInstance() {
        // Required empty public constructor
        ChangePhoneFragment fragment = new ChangePhoneFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_change_phone, container, false);
        ButterKnife.bind(this, view);
        initToolbar();
        initView();
        initRequest();
        editListener();
        return view;
    }


    private void editListener() {
        changePhoneMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 11) {
                    checkReg(editable.toString());//检查号码是否已经注册了
                }
            }

        });
    }

    private void initToolbar() {
        toolbar.setTitle("更改手机号");
        initToolbarNav(toolbar);
    }

    //检测是否注册
    private void checkReg(String s) {
        HashMap map = new HashMap();
        map.put("mobile", s);
        String sign = Encoder.getSigns(map);
        LoginDataHttpRequest.getInstance(MyApp.getApp()).postCheckReg(
                new ProgressSubscriber(subscriberReg, _mActivity), s, sign);

    }
    private void initView() {
        changePhoneYzm.setImageBitmap(Rotate.getInstance().createBitmap());
    }

    private void initRequest() {

        //是否注册
        subscriberReg = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {
            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                data = entity;
                ToastUtil.showToast(_mActivity, "手机号未注册");
                flag = 1;
            }
        };
        //验证码
        subscriberCode = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {

            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                data = entity;
                ToastUtil.showToast(_mActivity,"验证码发送成功");
                token = data.getToken();
            }
        };

        //找回密码
        subscriber = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {
            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                //接口请求成功后处理
                EventBus.getDefault().post(new StartFragmentEvent(ChangeSuccessfullyFragment.newInstance()));

            }
        };
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.change_phone_yzm, R.id.change_phone_msg, R.id.change_phone_sumit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.change_phone_yzm:
                initView();
                break;
            case R.id.change_phone_msg:
                sendMsgCode();
                break;
            case R.id.change_phone_sumit:
                submit();
                break;
        }
    }

    private void submit() {
        String mobile = changePhoneMobile.getText().toString().trim();//手机号
        String tuxing = changePhoneTuxing.getText().toString().trim();//图形验证码
        String vcode = changePhoneEtMsg.getText().toString().trim();//验证码
        Map<String,String> map = new HashMap<>();
        map.put("mobile",mobile);
        map.put("vcode",vcode);
        map.put("msgToken",token);
        String sign = Encoder.getSigns(map);

        if (TextUtils.isEmpty(mobile)||mobile.length()<11 ) {
            ToastUtil.showToast(_mActivity,"请输入正确手机号码");
            return;
        }

        if (flag != 1){
            ToastUtil.showToast(_mActivity,"请输入正确手机号码");
        }
        if (!ValidatorUtils.isMobile(mobile)) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
            return;
        }

        if(!Rotate.getInstance().getCode().toUpperCase().equals(tuxing.toUpperCase())){
            ToastUtil.showToast(_mActivity,"图形验证码错误");
            return;
        }

        if (TextUtils.isEmpty(vcode)) {
            ToastUtil.showToast(_mActivity,"请按要求输入验证码");
            return;
        }

        if (TextUtils.isEmpty(token)) {
            ToastUtil.showToast(_mActivity,"请发送验证短信");
            return;
        }

        LoginDataHttpRequest.getInstance(MyApp.getApp()).postModifyPhone(new ProgressSubscriber(subscriber,_mActivity),
                mobile,vcode,token,sign);
    }

    private void sendMsgCode() {
        String mobile = changePhoneMobile.getText().toString().trim();//手机号
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
        }
        if (!ValidatorUtils.isMobile(mobile)) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
        } else {
            //发送验证码请求
            int reg = 2;
            Map<String,String> map = new HashMap<>();
            map.put("mobile",mobile);
            map.put("reg",reg+ "");
            String sign = Encoder.getSigns(map);

            LoginDataHttpRequest.getInstance(MyApp.getApp()).postSendSms(
                    new ProgressSubscriber(subscriberCode,_mActivity),mobile,reg,sign);
            changePhoneMsg.setText("重新获取(" + time + ")");
            changePhoneMsg.setClickable(false);
            handler.sendEmptyMessageDelayed(100, 1000);
        }
    }
}
